package com.appspot.checkflames.servlet;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.appspot.checkflames.constants.CheckFlamesConstants.*;

public class AllowAccessServlet extends HttpServlet {
	
	/**
	 * Generated serial version uid.  
	 */
	private static final long serialVersionUID = -5728325938856243996L;

	private static final String LOGIN_URL = "http://www.facebook.com/login.php";
	
	private static String APPLICATION_KEY;
	
	private static String APPLICATION_HOME_URL;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		StringBuilder allowAccessUrl = new StringBuilder(LOGIN_URL);
		allowAccessUrl.append(QUESTION_MARK);
		allowAccessUrl.append(APP_KEY);
		allowAccessUrl.append(EQUAL_SIGN);
		allowAccessUrl.append(APPLICATION_KEY);
		allowAccessUrl.append(AMPERSAND_SIGN);
		allowAccessUrl.append("v=1.0&");
		allowAccessUrl.append("next");
		allowAccessUrl.append(EQUAL_SIGN);
		allowAccessUrl.append(URLEncoder.encode(APPLICATION_HOME_URL,"UTF-8"));
		allowAccessUrl.append(AMPERSAND_SIGN);
		allowAccessUrl.append("canvas=1");
		
		String url = "http://www.facebook.com/login.php?api_key=2261480057da5eae3bde48d6fca99a81&display=page&session_version=3&fbconnect=1&req_perms=publish_stream&return_session=1&v=1.0&next=http://apps.facebook.com/check_flames/&cancel_url=http://apps.facebook.com/check_flames/";
		
		resp.sendRedirect(url);
	}
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		APPLICATION_KEY = config.getInitParameter(APPLICATION_ID_PARAM);
		APPLICATION_HOME_URL = config.getInitParameter(APP_HOME_URL_PARAM);
	}
}
